import {
  setTagNavListInLocalstorage,
  getMenuByRouter,
  getTagNavListFromLocalstorage,
  getHomeRoute,
  getNextRoute,
  routeHasExist,
  routeEqual,
  getRouteTitleHandled,
  localRead
} from '@/libs/util'
import router from '@/router'
import routers from '@/router/routers'
import config from '@/config'
const { homeName } = config

const closePage = (state, route) => {
  const nextRoute = getNextRoute(state.tagNavList, route)
  state.tagNavList = state.tagNavList.filter(item => {
    return !routeEqual(item, route)
  })
  router.push(nextRoute)
}

export default {
  state: {
    tagNavList: [],
    homeRoute: {},
    local: localRead('local'),
    loading: 0
  },
  getters: {
    menuList: (state, getters, rootState) =>
      getMenuByRouter(routers, rootState.user.access),
    errorCount: state => state.errorList.length,
    loading: state => state.loading
  },
  mutations: {
    setHomeRoute(state, routes) {
      state.homeRoute = getHomeRoute(routes, homeName)
    },
    setTagNavList(state, list) {
      let tagList = []
      if (list) {
        tagList = [...list]
      } else tagList = getTagNavListFromLocalstorage() || []
      if (tagList[0] && tagList[0].name !== homeName) tagList.shift()
      let homeTagIndex = tagList.findIndex(item => item.name === homeName)
      if (homeTagIndex > 0) {
        let homeTag = tagList.splice(homeTagIndex, 1)[0]
        tagList.unshift(homeTag)
      }
      state.tagNavList = tagList
      setTagNavListInLocalstorage([...tagList])
    },
    closeTag(state, route) {
      let tag = state.tagNavList.filter(item => routeEqual(item, route))
      route = tag[0] ? tag[0] : null
      if (!route) return
      closePage(state, route)
    },
    addTag(state, { route, type = 'unshift' }) {
      let router = getRouteTitleHandled(route)
      if (!routeHasExist(state.tagNavList, router)) {
        if (type === 'push') state.tagNavList.push(router)
        else {
          if (router.name === homeName) state.tagNavList.unshift(router)
          else state.tagNavList.splice(1, 0, router)
        }
        setTagNavListInLocalstorage([...state.tagNavList])
      }
    },
    SET_LOADING(state, status) {
      if (0 === status) {
        state.loading = 0
        return
      }
      state.loading = status ? ++state.loading : --state.loading
    },
    ADD_UNIQUE_TAG(state, { route, type = 'unshift' }) {
      let router = getRouteTitleHandled(route)
      // 首先判断当前路由在tags中是否存在：
      // 1.列表页：name存在直接跳转，无需处理
      // 2.新增或者编辑：name存在，先关闭之前的tag，然后重新打开
      // 3.详情：name query params有一个不相同就打开一个新的
      const name = router.name
      if (name.indexOf('-detail') > -1) {
        // 详情处理
        if (!routeHasExist(state.tagNavList, router)) {
          if (type === 'push') state.tagNavList.push(router)
          else {
            if (router.name === homeName) state.tagNavList.unshift(router)
            else state.tagNavList.splice(1, 0, router)
          }
          setTagNavListInLocalstorage([...state.tagNavList])
        }
      } else if (name.indexOf('-add') > -1 || name.indexOf('-edit') > -1) {
        // 新增或者编辑处理
        const hasExistRouteIndex = state.tagNavList.findIndex(
          item => item.name === name
        )

        if (hasExistRouteIndex > -1) {
          const hasExistRoute = state.tagNavList[hasExistRouteIndex]
          if (!routeEqual(router, hasExistRoute)) {
            // let tag = state.tagNavList.filter(item =>
            //   routeEqual(item, hasExistRoute)
            // )
            // route = tag[0] ? tag[0] : null
            // if (!route) return
            // closePage(state, route)
            // state.tagNavList.push(router)
            state.tagNavList.splice(hasExistRouteIndex, 1, router)
          }
        } else {
          state.tagNavList.push(router)
        }
        setTagNavListInLocalstorage([...state.tagNavList])
      } else {
        // 列表处理
        if (!routeHasExist(state.tagNavList, router)) {
          if (type === 'push') state.tagNavList.push(router)
          else {
            if (router.name === homeName) state.tagNavList.unshift(router)
            else state.tagNavList.splice(1, 0, router)
          }
          setTagNavListInLocalstorage([...state.tagNavList])
        }
      }
    },
    RESET_TAGS(state) {
      state.tagNavList = []
    }
  },
  actions: {
    SetLoading({ commit }, status) {
      commit('SET_LOADING', status)
    },
    AddUniqueTag({ commit }, tagRoute) {
      commit('ADD_UNIQUE_TAG', tagRoute)
    },
    ResetTags({ commit }) {
      commit('RESET_TAGS')
    }
  }
}
